from django.db import models
from pydocx import PyDocX
from django.utils.safestring import mark_safe
import codecs
import markdown

# Create your models here.
# Group Model
class Group(models.Model):
    group = models.CharField(max_length=36)
    def __str__(self):
        return self.group

    def member(self):
        return ','.join([str(m) for m in self.member_set.all()])

# Member Model
class Member(models.Model):
    member = models.CharField(max_length=36)  # 姓名
    number = models.CharField(max_length=12)  # 学号, 用在动态URL
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    def __str__(self):
        return self.group.__str__() + '_' +self.member

# Week Model
class Week(models.Model):
    week = models.PositiveSmallIntegerField(default=0)  # 第几周周数
    def __str__(self):
        return str(self.week)

    def article(self):
        return ','.join([str(a) for a in self.article_set.all()])

# Year Model
class Year(models.Model):
    year = models.CharField(max_length=4, default='1970')
    first_half = models.PositiveSmallIntegerField(default=1)  # 1为上半年, 2为下半年
    def __str__(self):
        if self.first_half == 1:
            return self.year + '上半年'
        elif self.first_half == 2:
            return self.year + '下半年'

# Article Model
class Article(models.Model):
    member = models.ForeignKey(Member, on_delete=models.CASCADE)  # 所属成员
    week = models.ForeignKey(Week, on_delete=models.CASCADE)  # 周数
    year = models.ForeignKey(Year, on_delete=models.CASCADE)  # 今年下半年, 直接开花
    top = models.BooleanField(default=False)  # 是否置顶, 默认为否
    click = models.PositiveIntegerField(default=0)  # 点击量
    upload_time = models.DateTimeField(auto_now_add=True)  # 最初上传时间
    edited_time = models.DateTimeField(auto_now=True)  # 最后修改时间
    doc = models.FileField(upload_to='document/doc/%Y/%m/%d', blank=True, null=True)  # .docx 文档
    md = models.FileField(upload_to='document/md/%Y/%m/%d', blank=True, null=True)  # markdown 文档

    def __str__(self):
        return str(self.member)

    def click_increase(self):
        self.click += 1
        self.save(update_fields=['click'])

    def docxToHTML(self):
        doc_html = PyDocX.to_html(self.doc.path)
        doc_html = doc_html.replace('<html>', '').replace('</html>', '').replace('<head>', '').replace('</head>', '')
        doc_html = doc_html.replace('<meta charset="utf-8" />', '').replace('<body>', '').replace('</body>', '')
        start = doc_html.find('</style>')
        style = doc_html[:start + 8]
        doc_html = doc_html.replace(style, '')
        doc_html = mark_safe(doc_html)

        return doc_html

    def mdToHTML(self):
        input_file = codecs.open(self.md.path, mode="r", encoding="utf-8")
        text = input_file.read()
        md_html = markdown.markdown(text)
        md_html = mark_safe(md_html)

        return md_html